<template>
  <div class="bigbox">
    <div class="liftbox">
      <div style="margin-left: 4px">
        <template>
          <!-- <el-select ref="select" clearable
             @change="cahange"
             v-model="input1" filterable placeholder="请选择" @keyup.enter.native="changinput1" style="width: 280px;">
                <el-option
                class="select"
                  v-for="item in options"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select> -->
          <el-autocomplete
            class="inline-input"
            v-model="filterText"
            style="margin-bottom: 10px; width: 100%"
            :fetch-suggestions="querySearch"
            placeholder="输入关键字进行过滤"
            :trigger-on-focus="true"
            value-key="name"
            :debounce="300"
            @select="handleSelect"
          ></el-autocomplete>
        </template>
      </div>
      <div class="treebox">
        <!-- 树状图区域结构 -->
        <el-tree
          :props="props"
          :load="loadNode"
          node-key="id"
          accordion
          :highlight-current="true"
          :default-expanded-keys="array"
          lazy
          @node-click="handleNodeClick"
          ref="tree"
        >
          <template slot-scope="{ node, data }">
            <span
              :style="{
                color: data.collect
                  ? ''
                  : data.className == 'FactoryStation'
                  ? '#999'
                  : '',
                'font-size': data.collect
                  ? ''
                  : data.className == 'FactoryStation'
                  ? '14px'
                  : '',
              }"
            >
              <img
                :src="'data:image/png;base64,' + data.iconBase64"
                style="
                  width: 16px;
                  height: 16px;
                  margin-right: 5px;
                  vertical-align: bottom;
                "
              />{{ node.label }}</span
            >
          </template>
        </el-tree>
      </div>
    </div>
    <div class="rightbox">
      <div class="title">{{ row.name }} 测点列表</div>
      <div class="righttop">
        <div>
          <template>
            <el-select
              v-model="form.region"
              clearable
              placeholder="测点分组"
              size="medium"
              style="margin-right: 10px"
              @change="changeselectdan"
            >
              <el-option
                class="select"
                v-for="(item, index) in xlalalist"
                :key="index"
                :label="item.text"
                :value="item.value"
              ></el-option>
            </el-select>
            <el-input
              placeholder="请输入测点名称搜索"
              suffix-icon="el-icon-search"
              @keyup.enter.native="changeinput"
              v-model="input2"
              style="width: 200px; height: 32px"
              size="medium"
            ></el-input>
          </template>
        </div>
        <div class="button">
          <el-dropdown @command="handleCommand">
            <el-button type="primary" style="background-color: #409eff">
              新增<i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="moban" style="padding: 0 10px"
                ><span>模板方式</span></el-dropdown-item
              >
              <el-dropdown-item command="fuzhi" style="padding: 0 10px"
                ><span>复制方式</span></el-dropdown-item
              >
              <el-dropdown-item command="zhiyou" style="padding: 0 10px"
                ><span>自由方式</span></el-dropdown-item
              >
            </el-dropdown-menu>
          </el-dropdown>
          <span @click="newxuni"
            ><button style="cursor: pointer; width: auto; padding: 0 10px">
              新增虚拟测点
            </button></span
          >
          <span @click="pilianggai"
            ><button style="cursor: pointer">批量修改</button></span
          >
          <span @click="dellist"
            ><button style="cursor: pointer">批量删除</button></span
          >
        </div>
      </div>
      <div class="tablebox">
        <template>
          <el-table
            ref="multipleTable"
            :data="tableData"
            tooltip-effect="dark"
            style="width: 100%"
            border
            height="calc(100% - 1px)"
            :header-cell-style="{
              background: '#f5f5f5',
              'text-align': 'center',
            }"
            @selection-change="handleSelectionChange"
          >
            <template slot="empty">
              <el-empty description="暂无数据"></el-empty>
            </template>
            <el-table-column type="selection" width="55" align="center">
            </el-table-column>
            <el-table-column label="采集设备" prop="iotSourceName">
            </el-table-column>
            <el-table-column prop="itemTag" label="测点标识"> </el-table-column>
            <el-table-column prop="itemName" label="测点名称">
            </el-table-column>
            <el-table-column label="测点地址" prop="dataAddress">
            </el-table-column>
            <el-table-column prop="dataRate" label="倍率" align="right">
            </el-table-column>
            <el-table-column prop="itemGroup" label="测点分组" align="center">
              <template #default="{ row }">
                <span>{{
                  xlalalist.filter((ele) => ele.value == row.itemGroup)[0]?.text
                }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="address" label="操作" align="center">
              <template #default="{ row }">
                <el-tooltip
                  class="item"
                  effect="dark"
                  content="修改"
                  placement="top-end"
                >
                  <span @click="putlists(row)"
                    ><i
                      class="el-icon-edit"
                      style="color: skyblue; margin-left: 15px; cursor: pointer"
                    ></i
                  ></span>
                </el-tooltip>
                <el-tooltip
                  class="item"
                  effect="dark"
                  content="删除"
                  placement="top-end"
                >
                  <span @click="dellist(row)"
                    ><i
                      class="el-icon-delete"
                      style="color: red; margin-left: 15px; cursor: pointer"
                    ></i
                  ></span>
                </el-tooltip>
                <el-tooltip
                  class="item"
                  effect="dark"
                  content="上移"
                  placement="top-end"
                >
                  <span @click="shangyi(row)"
                    ><i
                      class="el-icon-upload2"
                      style="color: skyblue; margin-left: 15px; cursor: pointer"
                    ></i
                  ></span>
                </el-tooltip>
                <el-tooltip
                  class="item"
                  effect="dark"
                  content="下移"
                  placement="top-end"
                >
                  <span @click="xiayi(row)"
                    ><i
                      class="el-icon-download"
                      style="color: skyblue; margin-left: 15px; cursor: pointer"
                    ></i
                  ></span>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </div>
    </div>
    <!-- 模板新增弹出框 -->
    <DialogMuban
      :value="value"
      ref="dialogmuban"
      :row="row ? row : {}"
      @shuxing="shuxing"
    ></DialogMuban>
    <!-- 非模板新增弹出框 -->
    <DialogFeimuban
      :value="value"
      ref="dialogfeimuban"
      :row="row ? row : {}"
      @shuxing="shuxing"
    ></DialogFeimuban>
    <!-- 批量修改遥测数据类型组件 -->
    <DialogYaoce
      ref="dialogyaoce"
      :flag="'flag'"
      :changeselect="changeselect"
      @shuxing="shuxing"
    >
    </DialogYaoce>
    <!-- 批量修改遥信数据类型组件 -->
    <DialogYaoxin
      ref="dialogyaoxin"
      :changeselect="changeselect"
      :flag="'flag'"
      @shuxing="shuxing"
    ></DialogYaoxin>
    <!-- 批量修改累计数据类型组件 -->
    <DialogLeiji
      ref="dialogleiji"
      :changeselect="changeselect"
      :flag="'flag'"
      @shuxing="shuxing"
    >
    </DialogLeiji>
    <!-- 批量修改遥控数据类型组件 -->
    <DialogYaokong
      ref="dialogyaokong"
      :changeselect="changeselect"
      :flag="'flag'"
      @shuxing="shuxing"
    ></DialogYaokong>
    <!-- 批量修改遥调数据类型组件 -->
    <DialogYaotiao
      ref="dialogyaotiao"
      :changeselect="changeselect"
      :flag="'flag'"
      @shuxing="shuxing"
    ></DialogYaotiao>
    <!-- 复制新增弹出框 -->
    <div>
      <el-dialog title="复制新增" :visible.sync="dialogVisibles" width="30%">
        <div>
          <el-form :model="formdata" :rules="rules" ref="form">
            <el-form-item label="复制设备:" prop="fuzhi">
              <el-select
                v-model="formdata.fuzhi"
                placeholder="请选择复制设备"
                filterable
                style="width: 250px"
                size="mini"
                ref="selects"
              >
                <template v-slot:prefix>
                  <span>从</span>
                </template>
                <el-option
                  class="select"
                  v-for="(item, index) in xlalalists"
                  :key="index"
                  :label="item.text"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="采集设备:" prop="caiji">
              <el-select
                v-model="formdata.caiji"
                placeholder="请选择采集设备"
                filterable
                style="width: 250px"
                size="mini"
              >
                <template v-slot:prefix>
                  <span>至</span>
                </template>
                <el-option
                  class="select"
                  v-for="(item, index) in xlalalistss"
                  :key="index"
                  :label="item.text"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </div>
        <span slot="footer" class="button">
          <button
            class="sure"
            type="primary"
            @click="submit"
            style="cursor: pointer"
          >
            确 定
          </button>
          <button @click="quxiaofuzhi" style="cursor: pointer">取 消</button>
        </span>
      </el-dialog>
    </div>
    <!-- 虚拟测点新增 -->
    <div>
      <XniCedian
        ref="xunicedian"
        :value="value"
        @shuaxin="shuaxin"
        :isxunicedianobj="isxunicedianobj"
        @qingkong="isxunicedianobj = {}"
      ></XniCedian>
    </div>
  </div>
</template>

<script>
import { getxialafenzuapi } from "../../api/eventtype.js";
import {
  getshebeilistapi,
  getgenjiedianapi,
  getzijidianapi,
  getsousuoapi,
  getfuzhiapi,
  getcaijiapi,
  postfuzizenapi,
  dellistapi,
  postshangyiapi,
  postxiayiapi,
} from "@/api/device";
import DialogMuban from "@/views/device/mubanxin.vue";
import DialogFeimuban from "@/views/device/feimuban.vue";
import DialogYaoce from "@/views/measure/yaoce.vue";
import DialogYaoxin from "@/views/measure/yaoxin.vue";
import DialogLeiji from "@/views/measure/leiji.vue";
import DialogYaokong from "@/views/measure/yaokong.vue";
import DialogYaotiao from "@/views/measure/yaotiao.vue";
import XniCedian from "@/views/device/xunicedian.vue";
export default {
  name: "MaintenanceIndex",
  components: {
    DialogMuban,
    DialogFeimuban,
    DialogYaoce,
    DialogYaoxin,
    DialogLeiji,
    DialogYaokong,
    DialogYaotiao,
    XniCedian,
  },
  data() {
    return {
      formdata: {},
      rules: {
        fuzhi: [{ required: true, message: "复制设备必选", trigger: "blur" }],
        caiji: [{ required: true, message: "采集设备必选", trigger: "blur" }],
      },
      props: {
        label: "name",
        children: "children",
        isLeaf: "leaf",
      },
      dialogVisibles: false,
      treedata: {},
      xlalalist: [],
      form: {},
      val: "",
      input1: "",
      input2: "",
      tableData: [],
      value: "",
      options: [],
      option: [],
      row: "",
      xlalalists: [],
      xlalalistss: [],
      mulist: [],
      changeselect: [],
      filterlist: [],
      isxunicedianobj: {},
      array: ["503750"],
      filterText: "",
    };
  },
  async created() {},
  async mounted() {
    const res = await getxialafenzuapi({ dictType: "MeasurementKind" });
    this.xlalalist = res.data.list;
    // const ress = await getgenjiedianapi({ treeModel: 'MbmDeviceManageTree' })
    // const ress = await getgenjiedianapi({ treeModel: 'ENERGY_SET_TREE' })
    // this.row = ress.data.list[0]
  },
  methods: {
    async getcaijixialalist(id) {
      try {
        const ress = await getfuzhiapi({ deviceId: id });
        this.xlalalists = ress.data.list;
      } catch (error) {
        this.xlalalists = [];
      }
      try {
        const resss = await getcaijiapi({ deviceId: id });
        this.xlalalistss = resss.data.list;
        //  this.xlalalistss.forEach(ele=>this.filterlist.push(ele))
      } catch (error) {
        this.xlalalistss = [];
      }
    },
    async loadNode(node, resolve) {
      const res = await getgenjiedianapi({ treeModel: "ENERGY_SET_TREE" });
      const ress = await getzijidianapi(res.data.list[0]);
      // console.log(ress)
      if (node.level === 0) {
        this.row = ress.data.list[0];
        return resolve(ress.data.list);
      } else if (node.level === 1) {
        const ress = await getzijidianapi(node.data);
        return resolve(ress.data.list);
      } else if (node.level === 2) {
        const ress = await getzijidianapi(node.data);
        return resolve(ress.data.list);
      } else if (node.level === 3) {
        const ress = await getzijidianapi(node.data);
        return resolve(ress.data.list);
      } else if (node.level === 4) {
        const ress = await getzijidianapi(node.data);
        return resolve(ress.data.list);
      } else if (node.level === 5) {
        const ress = await getzijidianapi(node.data);
        return resolve(ress.data.list);
      }
    },
    async getshebeilist(number, val) {
      // 目前树状图数据没有，deviceId参数暂时写死
      const res = await getshebeilistapi({
        deviceId: number,
        itemGroup: val || "",
      });
      this.tableData = res.data.list;
    },
    handleNodeClick(val) {
      this.row = val;
      this.value = val.id;
      this.getcaijixialalist(val.id);
      this.getshebeilist(val.id, this.val);
    },
    handleSelectionChange(val) {
      this.changeselect = val;
      this.mulist = val.map((ele) => ele.id);
    },
    changeselectdan(val) {
      this.val = val;
      this.getshebeilist(this.value, val);
    },
    changeinput() {
      this.tableData = this.tableData.filter(
        (ele) => ele.itemName.indexOf(this.input2) !== -1
      );
    },
    handleSelect(val) {
      console.log(val, 555);
    },
    // ---------------------
    async changinput1() {
      // this.options = this.option.filter(ele => ele.name.indexOf(this.$refs.select.query) !== -1)
      const res = await getsousuoapi({ name: this.$refs.select.query });
      this.options = res.data.list;
      console.log(res.data.list);
    },
    shuxing() {
      this.getshebeilist(this.value, this.val);
    },
    async submit() {
      await this.$refs.form.validate();
      this.dialogVisibles = false;
      await postfuzizenapi({
        deviceId: this.row.id,
        iotDeviceId: this.formdata.caiji,
        referDeviceId: this.formdata.fuzhi,
      });
      this.getshebeilist(this.value, this.val);
      this.$message.success("复制成功");
      this.$refs.form.resetFields();
    },
    quxiaofuzhi() {
      this.dialogVisibles = false;
      this.$refs.form.resetFields();
    },
    dellist(row) {
      if (!this.mulist[0] && !row.id) return this.$message.warning("请先勾选");
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          if (row.id) {
            await dellistapi({ id: [row.id] });
          } else {
            await dellistapi({ id: this.mulist });
          }
          this.getshebeilist(this.value, this.val);
          this.$message.success("删除成功");
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    pilianggai() {
      console.log(this.changeselect);
      if (this.changeselect.length === 0) {
        return this.$message.warning("请先勾选");
      }
      if (this.changeselect.every((ele) => ele.dataType === "YC")) {
        this.$refs.dialogyaoce.dialogVisible = true;
        console.log("yc");
      } else if (this.changeselect.every((ele) => ele.dataType === "YX")) {
        this.$refs.dialogyaoxin.dialogVisible = true;
        console.log("yx");
      } else if (this.changeselect.every((ele) => ele.dataType === "LJ")) {
        this.$refs.dialogleiji.dialogVisible = true;
        console.log("lj");
      } else if (this.changeselect.every((ele) => ele.dataType === "YK")) {
        this.$refs.dialogyaokong.dialogVisible = true;
        console.log("yk");
      } else if (this.changeselect.every((ele) => ele.dataType === "YT")) {
        console.log("yt");
        this.$refs.dialogyaotiao.dialogVisible = true;
      } else {
        this.$message.warning("请勾选同一数据类型的数据进行批量修改");
      }
    },

    // 树节点搜索
    async querySearch(queryString, cb) {
      setTimeout(async () => {
        const res = await getsousuoapi({ name: queryString });
        const restaurants = res.data.list;
        cb(restaurants);
      }, 500);
      // 调用 callback 返回建议列表的数据
    },
    // 搜索选择
    handleSelect(item) {
      // this.array=['503750']
      const newarr = item.pathId.split(",");
      for (let i = 0; i < newarr.length; i++) {
        if (newarr[i]) {
          this.array.push(newarr[i]);
        }
      }
      function getgaoliang(that) {
        const node = that.$refs.tree.getNode(item);
        if (node) {
          that.$refs.tree.setCurrentKey(String(item.id));
        } else {
          setTimeout(() => {
            getgaoliang(that);
          }, 500);
        }
      }
      getgaoliang(this);
      this.value = item.id.toString();
      this.row = item;
      const namestring = item.name;
      this.row.name = namestring.replace(/\[.*?\]|\(.*?\)/g, "");
      this.getshebeilist(item.id, this.val);
    },

    putlists(row) {
      this.changeselect = [row];
      if (row.iotSource == "1") {
        this.$refs.xunicedian.dialogVisible = true;
        this.isxunicedianobj = row;
      } else if (row.dataType === "YC") {
        this.$refs.dialogyaoce.dialogVisible = true;
      } else if (row.dataType === "YX") {
        this.$refs.dialogyaoxin.dialogVisible = true;
      } else if (row.dataType === "LJ") {
        this.$refs.dialogleiji.dialogVisible = true;
      } else if (row.dataType === "YK") {
        this.$refs.dialogyaokong.dialogVisible = true;
      } else if (row.dataType === "YT") {
        this.$refs.dialogyaotiao.dialogVisible = true;
      }
    },
    newxuni() {
      this.value
        ? (this.$refs.xunicedian.dialogVisible = true)
        : this.$message.warning("请先选择测点设备");
    },
    shuaxin() {
      this.getshebeilist(this.value, this.val);
    },
    async shangyi(row) {
      await postshangyiapi({ id: row.id });
      this.$message.success("上移成功");
      this.getshebeilist(this.value, this.val);
    },
    async xiayi(row) {
      await postxiayiapi({ id: row.id });
      this.$message.success("下移成功");
      this.getshebeilist(this.value, this.val);
    },
    handleCommand(val) {
      console.log(val);
      if (val == "moban") {
        this.$refs.dialogmuban.dialogVisible = true;
      } else if (val == "fuzhi") {
        this.dialogVisibles = true;
      } else if (val == "zhiyou") {
        this.$refs.dialogfeimuban.dialogVisible = true;
      }
    },
  },
  watch: {
    input2(val) {
      if (!val) {
        this.getshebeilist(this.value, this.val);
      }
    },
    filterText(newValue) {
      this.filterText = newValue
        .replace(/^\[(.*?)\]/, "")
        .replace(/\((.*?)\)$/, "");
    },
  },
};
</script>

<style lang="scss" scoped>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
.bitton button {
  width: 63px;
  height: 32px;
  background-color: #fff;
  border: 1px solid #ccc;
  border-radius: 5px;
}
.sure {
  margin-right: 10px;
  background-color: #169bd5 !important;
  color: #fff;
}
.title {
  font-size: 18px;
  font-weight: 100px;
}
::v-deep.el-select-dropdown__empty {
  display: none;
}
::v-deep .el-select-dropdown__wrap {
  max-width: 280px !important;
}

.select {
  padding-left: 10px;
  width: 270px !important;
}
.tablebox {
  height: 88%;
  // background-color: yellow;
}
.bigbox {
  padding: 10px;
  background-color: #f1f1f1;
  display: flex;
  justify-content: space-between;
  height: 100%;
}
.liftbox {
  width: 300px;
  background-color: #fff;
  height: 100%;
  padding: 5px;
  box-sizing: border-box;
  // border-radius: ;
}
.rightbox {
  margin-left: 10px;
  background-color: #fff;
  width: calc(100% - 310px);
  // height:300px;
  padding: 5px 10px;
  box-sizing: border-box;
}
.righttop {
  display: flex;
  justify-content: space-between;
  margin: 10px 0;
}
.newzeng {
  background-color: #1890ff !important;
  color: #fff;
}
.button button {
  width: 75px;
  height: 30px;
  background-color: #fff;
  border-radius: 5px;
  border: 1px solid #ccc;
  margin-left: 5px;
}
.feixin {
  width: 95px !important;
}
.treebox {
  margin-top: 10px;
  width: 100%;
  height: calc(100% - 42px);
  // border:1px solid #ccc;
  overflow: hidden;
  overflow-y: auto;
}
::v-deep .el-tree-node__content {
  font-size: 14px; /* 修改为你想要的字体大小 */
}
::v-deep .el-input__suffix {
  cursor: pointer;
}
</style>
